package edu.must.uh.Generator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import edu.must.uh.util.SqlUtils;

public class JavaImplFileUtils {
    
    /**
     * 更新表结构
     */
    public static void updateJavaPOFile(){
        Map<String,TableInfo>tables=TableContext.tables;
        for(TableInfo tableInfo:tables.values()){
            createJavaPoFile(tableInfo,new MySQLTypeConvertor());
        }
    }  

    /**
     * 根据表信息生成java源码
     * @param tableInfo 表信息
     * @param convertor 数据类型转换器
     * @return  java类的源代码
     */
    private static String createJavaSrc(TableInfo tableInfo,TypeConvertor convertor){
       
        Map<String,ColumnInfo>columns=tableInfo.getColumns();
        List<String> javaFields=new ArrayList<>();
        for (ColumnInfo columnInfo:columns.values()){           
            javaFields.add(columnInfo.getName());
        }
        String javaFieldString= javaFields.toString();
        javaFieldString = javaFieldString.replace("[", "").replace("]", "");        
        StringBuilder src=new StringBuilder();
        //生成package语句
        src.append("package "+ DBHepler.getConf().getPoPackage()+".impl;\n");
        //生成import语句
        src.append("import java.util.List;\r\n" + 
                "import java.util.Map;\r\n" + 
                "import com.alibaba.fastjson.JSON;\r\n" + 
                "import edu.must.uh.bean.BaseModulebutton;\r\n" + 
                "import edu.must.uh.util.BeanUtils;\r\n" + 
                "import edu.must.uh.util.JedisUtil;\r\n" + 
                "import edu.must.uh.util.MySqlUtils;\r\n" + 
                "import edu.must.uh.util.Tools;\r\n" + 
                "import edu.must.uh.util.ToolsOfString;  \n");     
        
        src.append(" \n \n \n");
        //生成类声明语句
        src.append("public class "+StringUtils.underlineToBigCamel(tableInfo.getTname())+"Impl extends BaseImpl {\n \n");              
        src.append("    public "+StringUtils.underlineToBigCamel(tableInfo.getTname())+"Impl() { \n ");
        src.append("    super.cashkey = \""+StringUtils.underlineToBigCamel(tableInfo.getTname())+"\"; \n ");
        src.append("    super.cashListkey = \""+StringUtils.underlineToBigCamel(tableInfo.getTname())+"List \"; \n ");
        src.append("    super.keyFields =\""+tableInfo.getOnlyPriKey().getName()+" \"; \n ");
        src.append("    super.tableName = \""+tableInfo.getTname()+"\"; \n ");
        src.append("  }  ");         
        src.append(" \n \n \n"); 
        
        src.append("   public List<Map<String, Object>> GetListByCache() throws Exception \n ");
        src.append("   { \n ");   
        src.append("   String strList=ToolsOfString.NulltoEmpty(JedisUtil.get(cashkey,cashListkey)) ; \n ");
        src.append("   if(strList.equals(\"\")) { \n ");
        src.append("      List<Map<String, Object>> resList = getList(null,null);  \n ");  
        src.append("      JedisUtil.set(cashkey, cashListkey, JSON.toJSONString(resList)); \n ");       
        src.append("      return  resList; \n ");        
        src.append("   }else{ \n ");           
        src.append("      List<Map<String, Object>> Ja = BeanUtils.parseJsonArrayStrToListForMaps(strList); \n ");      
        src.append("   return  Ja; \n ");                    
        src.append("    } \n ");           
        src.append("  }  ");                  
        src.append(" \n \n \n"); 
        
        src.append("  public List<Map<String, Object>> getList(Map<String, Object> searchcondition,String sqlcondition) throws Exception  \n "); 
        src.append("   { \n ");  
        src.append("    String sqlString = \"SELECT "+javaFieldString+" FROM "+tableInfo.getTname()+" Where 1 = 1 \"; \n "); 
        src.append("    sqlString = sqlString + Tools.getSQLCondition(searchcondition); \n "); 
        src.append("    sqlString = sqlString +ToolsOfString.NulltoEmpty(sqlcondition) ;  \n ");      
        src.append("    List<Map<String, Object>> resList = MySqlUtils.getlist(sqlString);  \n ");         
        src.append("  return  resList; \n ");             
        src.append("  } ");   
        src.append(" \n \n \n"); 
        
        
        src.append("  public Integer getCount(Map<String, Object> searchcondition,String sqlcondition) throws Exception  \n "); 
        src.append("   { \n ");  
        src.append("    String sqlString = \"SELECT count(*) as strcount FROM "+tableInfo.getTname()+" Where 1 = 1 \"; \n "); 
        src.append("    sqlString = sqlString + Tools.getSQLCondition(searchcondition); \n "); 
        src.append("    sqlString = sqlString +ToolsOfString.NulltoEmpty(sqlcondition) ;  \n ");      
        src.append("    List<Map<String, Object>> resList = MySqlUtils.getlist(sqlString);  \n ");         
        src.append("    return Integer.valueOf(resList.get(0).get(\"strcount\").toString()); \n ");             
        src.append("  } ");   
        src.append(" \n \n \n"); 
        
        src.append(" public Integer save("+StringUtils.underlineToBigCamel(tableInfo.getTname())+" bean) throws Exception \n ");  
        src.append(" { \n "); 
        src.append("   JedisUtil.del(cashkey); \n"); 
        src.append("   return MySqlUtils.save(tableName, bean); \n ");
        src.append(" } \n ");          
        src.append(" \n \n \n"); 
        
        src.append("\n\n");
        //生成结束符
        src.append("}");
        return src.toString();
    }

    /**
     * 生成java文件
     * @param tableInfo 表信息
     * @param convertor 类型转换器
     */
    private static void createJavaPoFile(TableInfo tableInfo,TypeConvertor convertor){
       
        String srcPath=DBHepler.getConf().getSrcPath()+"/";
        //将包名转换为文件名，然后和srcPath拼接
        String packagePath=DBHepler.getConf().getPoPackage().replace(".","/")+"/Impl";
        File f=new File(srcPath+packagePath);
        if (!f.exists()){
            f.mkdirs();
        }
        BufferedWriter bw=null;
        try {
            String filePth = f.getAbsoluteFile()+"/"+StringUtils.underlineToBigCamel(tableInfo.getTname())+"Impl.java";
            File file2 = new File(filePth);
            if(file2.exists()) {
                return ;
            }
            //获取源码
            String src=createJavaSrc(tableInfo,convertor);
            //将源码写入文件
            bw=new BufferedWriter(new FileWriter(filePth));
            bw.write(src);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

  
}
